package com.xmut.bs.handaccount.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.wyt.searchbox.custom.IOnSearchClickListener;
import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.activity.AddArticleActivity;
import com.xmut.bs.handaccount.activity.AdvWebActivity;
import com.xmut.bs.handaccount.activity.ArticleDetailActivity;
import com.xmut.bs.handaccount.base.BaseFragment;
import com.xmut.bs.handaccount.bmob.Adv;
import com.xmut.bs.handaccount.bmob.Article;
import com.xmut.bs.handaccount.util.DisplayUtils;
import com.xmut.bs.handaccount.util.DividerItemDecoration;
import com.xmut.bs.handaccount.util.GlideCircleTransform;
import com.xmut.bs.handaccount.util.StringUtil;
import com.xmut.bs.handaccount.widget.SearchBarView;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

import static com.xmut.bs.handaccount.base.Constants.PARAM_ADV_ACTION;
import static com.xmut.bs.handaccount.base.Constants.PARAM_ARTICLE_ID;
import static com.xmut.bs.handaccount.base.Constants.VERIFY_SUCCESS;

/**
 * Description
 * Created by Dollkey on 2018/4/7.
 */

public class HomeFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate, IOnSearchClickListener, View.OnClickListener {

    @BindView(R.id.search_bar)
    SearchBarView mSearchBar;
    @BindView(R.id.recycle_view)
    RecyclerView mRecycleView;
    @BindView(R.id.refresh_layout)
    BGARefreshLayout mRefreshLayout;
    @BindView(R.id.magic_indicator)
    MagicIndicator mMagicIndicator;
    @BindView(R.id.banner)
    BGABanner mBanner;

    private CommonAdapter<Article> mAdapter;
    private int pageNo;
    private int pageSize = 20;
    private List<Article> mList;
    private BmobQuery<Article> mBmobQuery;
//    private AddPopupWindow mAddPopupWindow;
    private BmobQuery<Adv> mBmobQueryAdv;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        mList = new ArrayList<>();
        mBmobQuery = new BmobQuery<>();
        mBmobQueryAdv = new BmobQuery<>();
        mSearchBar.setRightIvSrc(R.mipmap.ic_add);
        mSearchBar.setOnRightClickListener(this);
        mSearchBar.setIOnSearchListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        mRecycleView.setLayoutManager(layoutManager);
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setNestedScrollingEnabled(false);
        mRecycleView.setItemAnimator(new DefaultItemAnimator());
        mRecycleView.addItemDecoration(new DividerItemDecoration(mContext,
                DisplayUtils.dp2px(mContext, 8),
                getResources().getColor(R.color.grey100)).setHasLeftOrRight(false).setHasTopAndBottom(false));
//        initMagicIndicator();
        initRefreshLayout(mRefreshLayout, this);
        mRefreshLayout.beginRefreshing();
    }

    @Override
    public void onClick(View view) {
        startActivity(new Intent(mContext, AddArticleActivity.class));
//        if (mAddPopupWindow == null) {
//            mAddPopupWindow = new AddPopupWindow(mContext);
//        }
//        mAddPopupWindow.show();
    }


    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        pageNo = 0;
        mList.clear();
        query();
        queryBanner();
    }

    private void queryBanner() {
        mBmobQueryAdv.order("order");
        mBmobQueryAdv.findObjects(new FindListener<Adv>() {
            @Override
            public void done(List<Adv> list, BmobException e) {
                if (e == null) {
                    if (list.size() == 0) {
                        mBanner.setVisibility(View.GONE);
                        return;
                    }
                    mBanner.setAdapter(new BGABanner.Adapter<ImageView, Adv>() {
                        @Override
                        public void fillBannerItem(BGABanner banner, ImageView itemView, final Adv adv, int position) {
                            GlideApp.with(mContext)
                                    .load(adv.getImgUrl())
                                    .placeholder(R.color.grey200)
                                    .error(R.color.grey200)
                                    .centerCrop()
                                    .dontAnimate()
                                    .into(itemView);
                            itemView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent().putExtra(PARAM_ADV_ACTION, adv.getAdvUrl()), AdvWebActivity.class);
                                }
                            });
                        }
                    });
                    if (list.size() > 1) {
                        mBanner.setAutoPlayAble(true);
                        mBanner.setAutoPlayInterval(2000);
                        mBanner.setAllowUserScrollable(true);
                    }
                    mBanner.setVisibility(View.VISIBLE);
                    mBanner.setData(list, null);
                } else {
                    mBanner.setVisibility(View.GONE);
                    showToast("请求失败：" + e.getMessage());
                }
            }
        });
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        pageNo++;
        query();
        return false;
    }

    private void query() {
        query("");
    }

    private void query(String key) {
        if (!StringUtil.isNull(key))
            mBmobQuery.addWhereEqualTo("title", key);
        else {
            mBmobQuery.addWhereNotEqualTo("title", "");
            mBmobQuery.setSkip(pageNo * pageSize);
            mBmobQuery.setLimit(pageSize);
        }
        mBmobQuery.order("-updatedAt");
        mBmobQuery.addWhereEqualTo("status", VERIFY_SUCCESS);
        mBmobQuery.include("user");
        mBmobQuery.findObjects(new FindListener<Article>() {
            @Override
            public void done(List<Article> list, BmobException e) {
                mRefreshLayout.endRefreshing();
                mRefreshLayout.endLoadingMore();
                if (e == null) {
                    mList.addAll(list);
                    setAdapter();
                } else {
                    showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    private void setAdapter() {
        if (mAdapter == null) {
            mAdapter = new CommonAdapter<Article>(mContext, R.layout.item_article, mList) {
                @Override
                protected void convert(ViewHolder holder, final Article article, int position) {
                    holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent().putExtra(PARAM_ARTICLE_ID, article), ArticleDetailActivity.class);
                        }
                    });
                    holder.setText(R.id.goods_name, article.getTitle());
                    holder.setText(R.id.username, article.getUser().getNickName());
                    holder.setVisible(R.id.start_video_img, article.getContainVideo());
                    ImageView coverImg = holder.getView(R.id.cover_img);
                    ImageView avatarImg = holder.getView(R.id.avatar_img);
                    GlideApp.with(coverImg).load(article.getCoverImg()).override(1200, 600).centerCrop().into(coverImg);
                    GlideApp.with(coverImg).load(article.getUser().getAvatar())
                            .placeholder(R.mipmap.ic_head_img).error(R.mipmap.ic_head_img)
                            .transform(new GlideCircleTransform(mContext)).override(60, 60).into(avatarImg);
                }
            };
            mRecycleView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void OnSearchClick(String keyword) {
        pageNo = 0;
        mList.clear();
        query(keyword);
    }

    private void initMagicIndicator() {
        final CommonNavigator commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setSkimOver(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            private List<String> mDataList = Arrays.asList("全部", "学霸", "清新", "文艺");

            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);

                // load custom layout
//                final View customLayout = LayoutInflater.from(context).inflate(R.layout.item_child_personal, null);
//                final TextView titleImg = customLayout.findViewById(R.id.up_img_tv);
//                final TextView titleText = customLayout.findViewById(R.id.down_tv);
//                titleImg.setTypeface(((BaseActivity) mContext).iconfont);
//                titleImg.setText(mRecommendList.get(index).getUrl());
//                titleText.setText(mRecommendList.get(index).getName());
//                commonPagerTitleView.setContentView(customLayout);

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                });

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
    }
}
